import com.hq.common.utils.EncrpytUtils;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 查看加密配置文件小工具
 * java -cp ti-core-1.0-SNAPSHOT.jar Main db.properties
 */
public class Main {
    //private static String OS_LINE_SEPARATOR = System.getProperty("line.separator");
    private static final String PROPERTIES_LINE_EQUAL_SPLIT = "=";
    private static final String ENCRPYT_KEY_BUNCH = "abcdefghigklmn123456opqrstuvwxyz";
    private static final String ENCRPYT_PREFIX = "{SGCC}";

    private static List<File> listFiles(File root, String targetName) {
        List<File> result = new ArrayList<File>();
        if (!root.exists()) {
            return result;
        }
        if (root.isDirectory()) {
            listSubFiles(result, root, targetName);
        } else {
            if (root.getName().equalsIgnoreCase(targetName)) {
                result.add(root);
            }
        }
        return result;
    }

    private static void listSubFiles(final List<File> result, File directory, final String targetName) {
        File[] files = directory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File subFile) {
                if (subFile.isDirectory()) {
                    listSubFiles(result, subFile, targetName);
                } else {
                    if (subFile.getName().contains(targetName)) {
                        return true;
                    }
                }
                return false;
            }
        });
        result.addAll(Arrays.asList(files));
    }

    private static String getPath() throws UnsupportedEncodingException {
        URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
        if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        }
        File file = new File(filePath);
        filePath = file.getAbsolutePath();//得到windows下的正确路径
        return filePath;
    }


    private static boolean isEncrpyted(String value) {
        return value.startsWith(ENCRPYT_PREFIX);
    }

    private static String getDecryptedValue(String value) {
        if (value != null && value.length() > 0) {
            if (isEncrpyted(value)) {//已经加密过
                try {
                    value = EncrpytUtils.decryptDES(value.replace(ENCRPYT_PREFIX, ""), ENCRPYT_KEY_BUNCH);
                } catch (Exception e) {
                    System.err.println("解密失败!");
                }
            }
        }
        return value;
    }

    private static void print(String propertiesPath) {
        List<String> lineList = new ArrayList<String>();
        try {
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(propertiesPath), "GBK"));
            String line, key, value;
            while ((line = bufReader.readLine()) != null) {
                line = line.trim();
                if (line.length() > 0) {
                    if (line.startsWith("#")) { //处理注释行
                        lineList.add(line);
                        continue;
                    }
                    String[] lineValue = line.split(PROPERTIES_LINE_EQUAL_SPLIT, 2);
                    if (lineValue.length == 2) {
                        key = lineValue[0];
                        value = lineValue[1];
                        if (isEncrpyted(value)) {
                            lineList.add(key + PROPERTIES_LINE_EQUAL_SPLIT + getDecryptedValue(value));
                        } else {
                            lineList.add(line);
                        }
                    } else {
                        System.err.println("Error Line:" + line);
                    }
                }
            }
            bufReader.close();
            for (String lineStr : lineList) {
                System.out.println(lineStr);
            }
        } catch (FileNotFoundException e) {
            System.err.println("file no found :" + propertiesPath);
        } catch (IOException e) {
            System.err.println("Parse Error!");
        }
    }

    public static void main(String[] args) throws Exception {
        if (args != null && args.length > 0) {
            final String targetName = args[args.length - 1];
            File pathFile = new File(targetName);
            if (pathFile.exists()) {
                print(targetName);
                return;
            }
            String path = getPath();
            pathFile = new File(path);
            File root = pathFile.getParentFile();
            System.out.println("【search file in " + root.getAbsolutePath() + ",target's name contain '" + targetName + "'】");
            List<File> result = listFiles(root, targetName);
            for (File file : result) {
                System.out.println("=============================    " + file.getAbsoluteFile() + "    =============================");
                print(file.getAbsolutePath());
            }
        } else {
            System.out.println("入参不正确!");
        }
    }
}
